package com.imau.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.imau.bean.*;
import com.imau.common.Const.PermissionConst;
import com.imau.common.exception.BusinessException;
import com.imau.mapper.PermissionApiMapper;
import com.imau.mapper.PermissionMapper;
import com.imau.mapper.PermissionMenuMapper;
import com.imau.mapper.PermissionPointMapper;
import com.imau.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper; //总表
    @Autowired
    private PermissionMenuMapper menuMapper; //菜单
    @Autowired
    private PermissionPointMapper pointMapper; //按钮
    @Autowired
    private PermissionApiMapper apiMapper; //api


    @Override
    public int savePermission(Map<String, Object> map) {

        //1.保存权限:总表
        //1.1 将map转换为permission对象
        Permission permission = BeanUtil.mapToBean(map, Permission.class, true);

        int row = permissionMapper.insert(permission);

        //1.2 将逐渐存储到map
        map.put("id", permission.getId());

        //2.保存权限的关联子表；
        int type = Integer.valueOf(map.get("type").toString());

        switch (type) {
            case PermissionConst.PERMISSION_MENU:
                row += menuMapper.insert(BeanUtil.mapToBean(map, PermissionMenu.class, true));
                break;
            case PermissionConst.PERMISSION_POIN:
                row += pointMapper.insert(BeanUtil.mapToBean(map, PermissionPoint.class, true));
                break;
            case PermissionConst.PERMISSION_API:
                row += apiMapper.insert(BeanUtil.mapToBean(map, PermissionApi.class, true));
                break;
        }

        return row;
    }

    @Override
    public int updatePermission(Map<String, Object> map) {

        int row = 0;

        //3.保存权限的关联子表；
        int type = Integer.valueOf(map.get("type").toString());

        switch (type) {
            case PermissionConst.PERMISSION_MENU:
                row += menuMapper.updateById(BeanUtil.mapToBean(map, PermissionMenu.class, true));
                break;
            case PermissionConst.PERMISSION_POIN:
                row += pointMapper.updateById(BeanUtil.mapToBean(map, PermissionPoint.class, true));
                break;
            case PermissionConst.PERMISSION_API:
                row += apiMapper.updateById(BeanUtil.mapToBean(map, PermissionApi.class, true));
                break;
        }

        //2.保存权限:总表
        row += permissionMapper.updateById(BeanUtil.mapToBean(map, Permission.class, true));

        return row;

    }

    @Override
    public Map<String, Object> findByPermissionId(String id) {

        Object bean = null;

        //1.定义map集合，存储查询结果
        Map<String, Object> map = new HashMap<>();
        //2. 查询总表
        Permission perm = permissionMapper.selectById(id);

        //3. 根据类型查询子表
        int type = perm.getType();

        if (type == PermissionConst.PERMISSION_MENU) {

            bean = menuMapper.selectById(id);

        } else if (type == PermissionConst.PERMISSION_POIN) {

            bean = pointMapper.selectById(id);

        } else if (type == PermissionConst.PERMISSION_API) {

            bean = apiMapper.selectById(id);

        } else {

            new BusinessException(10004, "数据类型不对");
        }

        map.putAll(BeanUtil.beanToMap(perm));

        map.putAll(BeanUtil.beanToMap(bean));

        return map;
    }


    @Override
    public List<Permission> findAllPermission(Permission permission) {


        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();

        if (permission != null) {
            queryWrapper.like(StringUtils.isNotEmpty(permission.getName()), Permission::getName, permission.getName());

            queryWrapper.eq(StringUtils.checkValNotNull(permission.getEnVisible()), Permission::getEnVisible, permission.getEnVisible());

            queryWrapper.eq(StringUtils.isNotEmpty(permission.getParentId()), Permission::getParentId, permission.getParentId());

            queryWrapper.eq(StringUtils.checkValNotNull(permission.getStatus()), Permission::getStatus, permission.getStatus());
            if (StringUtils.checkValNotNull(permission.getType()) && permission.getType() == 0) {
                queryWrapper.in(Permission::getType, Arrays.asList(1, 2));

            } else if (StringUtils.checkValNotNull(permission.getType()) && permission.getType() == 4) {
                queryWrapper.in(Permission::getType, Arrays.asList(1, 2, 3));
            } else {

                queryWrapper.in(Permission::getType, permission.getType());
            }


        }
        queryWrapper.orderByAsc(Permission::getOrderNum);

        //2.3 查询
        List<Permission> permissions = permissionMapper.selectList(queryWrapper);

        return this.buildPerTree(permissions);
    }

    @Override
    public List<Permission> buildPerTree(List<Permission> permissions) {
        List<Permission> returnList = new ArrayList<Permission>();
        List<String> tempList = permissions.stream().map(Permission::getId).collect(Collectors.toList());
        for (Permission permission : permissions) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(permission.getParentId())) {
                recursionFn(permissions, permission);
                returnList.add(permission);
            }
        }
        if (returnList.isEmpty()) {
            returnList = permissions;
        }
        return returnList;
    }

    @Override
    public List<TreeEntity> buildPerTreeSelect(List<Permission> permissions) {
        List<Permission> deptTrees = buildPerTree(permissions);
        return deptTrees.stream().map(TreeEntity::new).collect(Collectors.toList());
    }


    /**
     * 递归列表
     */
    private void recursionFn(List<Permission> list, Permission t) {
        // 得到子节点列表
        List<Permission> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Permission tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }


    /**
     * 得到子节点列表
     */
    private List<Permission> getChildList(List<Permission> list, Permission t) {
        List<Permission> tlist = new ArrayList<Permission>();
        Iterator<Permission> it = list.iterator();
        while (it.hasNext()) {
            Permission n = (Permission) it.next();
            if (StringUtils.isNotEmpty(n.getParentId()) && n.getParentId().equals(t.getId())) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Permission> list, Permission t) {
        return getChildList(list, t).size() > 0;
    }

    @Override
    public int deleteByPermissionId(String id) {


        //根据查询出权限对象
        Permission perm = permissionMapper.selectById(id);

        //获取类型
        int type = perm.getType();

        //先删除权限表
        int row = permissionMapper.deleteById(id);

        //类型表中删除
        if (type == PermissionConst.PERMISSION_MENU) {

            row += menuMapper.deleteById(id);

        } else if (type == PermissionConst.PERMISSION_POIN) {

            row += pointMapper.deleteById(id);

        } else if (type == PermissionConst.PERMISSION_API) {

            row += apiMapper.deleteById(id);

        }

        return row;
    }
}
